package com.erp.module.caiLiaoZhiLiang.xGCaiLiaoZhiLiang

import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.view.KeyEvent
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import com.erp.activity.BaseActivity
import com.erp.activity.DanjianivActivity
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.CaiLiaoPhotoKAdapter
import com.erp.bean.CaiLiaoZhiLiangBean
import com.erp.mclass.QuanXian
import com.erp.mclass.UnCeHandler
import com.erp.R
import com.erp.util.Dialogutil
import com.erp.util.Myutil
import com.erp.module.caiLiaoZhiLiang.CaiLiaoZhiLiangContract
import com.erp.module.caiLiaoZhiLiang.FragmentKCaiLiaoZhiLiang
import kotlinx.android.synthetic.main.activity_cailiao_zhiliang.*
import kotlinx.android.synthetic.main.header_knoya.view.*

class CaiLiaoZhiLiangActivity : BaseActivity(), CaiLiaoZhiLiangContract.XiuGaiCaiLiaoZhiLiangKView, View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {


    val a = "CaiLiaoZhiLiangActivity"
    lateinit var KP: CaiLiaoZhiLiangContract.XiuGaiCailiaoZhiliangKP
    lateinit var cailiaoIt: CaiLiaoZhiLiangBean
    lateinit var photoAdapter: CaiLiaoPhotoKAdapter
    lateinit var deletephoto: ArrayList<CaiLiaoZhiLiangBean.photo>
    var isXingJian = false
    lateinit var pandings: Array<String>
    lateinit var chulis: Array<String>
    var code = 0
    lateinit var updatedialog: AlertDialog
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_cailiao_zhiliang
    }

    override fun initCreate() {
        initView()
        initData()
    }

    private fun initView() {
        UnCeHandler.buzhou="initView"
        isXingJian = intent.getBooleanExtra("isXingJian", isXingJian)
        cailiaoIt = if (isXingJian) {
            CaiLiaoZhiLiangBean()
        } else {
            FragmentKCaiLiaoZhiLiang.it
        }
        deletephoto = ArrayList<CaiLiaoZhiLiangBean.photo>()
        KP = IXiugaiCailiaoZhiliangKP(this, this, cailiaoIt, isXingJian)
        Header.iv_header_left.visibility = View.VISIBLE
        Header.tv_header_title.text = "来料质量"
        if (QuanXian.isXiuGaiCaiLiaoZhiLiang) {
            Header.tv_header_right.visibility = View.VISIBLE
        }

    }

    private fun initData() {
        UnCeHandler.buzhou="initData"
        pandings = arrayOf("", "合格", "不合格")
        chulis = arrayOf("", "特采", "退货")
        val PDadapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, pandings)
        SpPanding.adapter = PDadapter
        val CLadapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, chulis)
        SpChuLi.adapter = CLadapter
        AtHuoping.setOnClickListener(this)
        AtWenTi.setOnClickListener(this)
        AtLeibie.setOnClickListener(this)
        AtGongyingshang.setOnClickListener(this)
        Header.tv_header_right.setOnClickListener(this)
        TvJianyanTimeX.setOnClickListener(this)
        Header.iv_header_left.setOnClickListener(this)

        photoAdapter = CaiLiaoPhotoKAdapter(cailiaoIt.listphoto, this)
        GvCailiaoPhoto.adapter = photoAdapter
        GvCailiaoPhoto.onItemClickListener = this
        GvCailiaoPhoto.onItemLongClickListener = this
        KP.getCailiaoLeibie()
        KP.getHuoping()
        KP.getGongyingshang()
        KP.getWentiDaima()
        if(!isXingJian){
            Myutil.settv(cailiaoIt.iu_name,TvGongyingshang)
            Myutil.setet(cailiaoIt.iu_name,AtGongyingshang)
            Myutil.settv(cailiaoIt.mc2_name,TvLeibie)
            Myutil.setet(cailiaoIt.mc2_name,AtLeibie)
            Myutil.settv(cailiaoIt.qi_name,TvWenTi)
            Myutil.settv(Myutil.getdata(cailiaoIt.jianyan_time),TvJianyanTime)
            Myutil.settv(Myutil.getdata(cailiaoIt.jianyan_time),TvJianyanTimeX)
            Myutil.settv(cailiaoIt.cailiao_shuliang,TvCailiao)
            Myutil.setet(cailiaoIt.cailiao_shuliang,EtCailiao)
            Myutil.settv(cailiaoIt.choucha_shuliang,TvChoucha)
            Myutil.setet(cailiaoIt.choucha_shuliang,EtChoucha)
            Myutil.settv(cailiaoIt.hege_shuliang,TvHege)
            Myutil.setet(cailiaoIt.hege_shuliang,EtHege)
            Myutil.settv(cailiaoIt.quality_decision,TvPanding)
            Myutil.settv(cailiaoIt.process_mode,TvChuLi)
            Myutil.settv(cailiaoIt.solution,TvCaigouJiejue)
            Myutil.setet(cailiaoIt.solution,EtCaigouJiejue)
            Myutil.settv(cailiaoIt.description,TvZhiliangYuanyou)
            Myutil.setet(cailiaoIt.description,EtZhiliangYuanyou)
            (0 until pandings.size)
                    .filter { cailiaoIt.quality_decision == pandings[it] }
                    .forEach { SpPanding.setSelection(it) }
            (0 until chulis.size)
                    .filter { cailiaoIt.process_mode == chulis[it] }
                    .forEach { SpChuLi.setSelection(it) }
        }
        if (isXingJian) {
            editJiemian()
        } else {
            viewJiemian()
        }
    }

    //查看时界面显示
    fun viewJiemian() {
        UnCeHandler.buzhou="viewJiemian"
        code = 1
        Header.tv_header_right.text = "修改"
        TvHuoping.visibility = View.VISIBLE
        TvGongyingshang.visibility = View.VISIBLE
        TvLeibie.visibility = View.VISIBLE
        TvWenTi.visibility = View.VISIBLE
        TvJianyanTime.visibility = View.VISIBLE
        TvCailiao.visibility = View.VISIBLE
        TvChoucha.visibility = View.VISIBLE
        TvHege.visibility = View.VISIBLE
        TvPanding.visibility = View.VISIBLE
        TvChuLi.visibility = View.VISIBLE
        TvCaigouJiejue.visibility = View.VISIBLE
        TvZhiliangYuanyou.visibility=View.VISIBLE
        AtHuoping.visibility = View.GONE
        AtGongyingshang.visibility = View.GONE
        AtLeibie.visibility = View.GONE
        AtWenTi.visibility = View.GONE
        TvJianyanTimeX.visibility = View.GONE
        EtCailiao.visibility = View.GONE
        EtChoucha.visibility = View.GONE
        EtHege.visibility = View.GONE
        SpPanding.visibility = View.GONE
        SpChuLi.visibility = View.GONE
        EtCaigouJiejue.visibility = View.GONE
        EtZhiliangYuanyou.visibility = View.GONE
    }

    //修改时界面显示
    fun editJiemian() {
        UnCeHandler.buzhou="editJiemian"
        code = 2
        Header.tv_header_right.text = "保存"
        TvHuoping.visibility = View.GONE
        TvGongyingshang.visibility = View.GONE
        TvLeibie.visibility = View.GONE
        TvWenTi.visibility = View.GONE
        TvJianyanTime.visibility = View.GONE
        TvCailiao.visibility = View.GONE
        TvChoucha.visibility = View.GONE
        TvHege.visibility = View.GONE
        TvPanding.visibility = View.GONE
        TvChuLi.visibility = View.GONE
        TvZhiliangYuanyou.visibility=View.GONE
        TvCaigouJiejue.visibility = View.GONE
        AtHuoping.visibility = View.VISIBLE
        AtGongyingshang.visibility = View.VISIBLE
        AtLeibie.visibility = View.VISIBLE
        AtWenTi.visibility = View.VISIBLE
        TvJianyanTimeX.visibility = View.VISIBLE
        EtCailiao.visibility = View.VISIBLE
        EtChoucha.visibility = View.VISIBLE
        EtHege.visibility = View.VISIBLE
        SpPanding.visibility = View.VISIBLE
        SpChuLi.visibility = View.VISIBLE
        EtCaigouJiejue.visibility = View.VISIBLE
        EtZhiliangYuanyou.visibility = View.VISIBLE
        photoAdapter.isadd(true)
        photoAdapter.notifyDataSetChanged()
    }

    override fun onClick(v: View?) {
        UnCeHandler.buzhou="onClick"
        when (v) {
            Header.iv_header_left -> finish()
            Header.tv_header_right -> {
                if (code == 1) {
                    editJiemian()
                } else if (code == 2) {
                    val bean = CaiLiaoZhiLiangBean()
                    if (!giNames.contains(AtHuoping.text.toString())) {
                        Myutil.MyTost("输入货品编码不存在,不能上传")
                        return
                    }
                    if (!iuNames.contains(AtGongyingshang.text.toString())) {
                        Myutil.MyTost("输入问的供应商不存在,不能上传")
                        return
                    }
                    if (!mc2Names.contains(AtLeibie.text.toString())) {
                        Myutil.MyTost("输入问的材料类别不存在,不能上传")
                        return
                    }
                    if (!qiNames.contains(AtWenTi.text.toString())) {
                        Myutil.MyTost("输入问的问题代码不存在,不能上传")
                        return
                    }
                    giNames.indices
                            .filter { i -> giNames[i] == AtHuoping.text.toString() }
                            .forEach { bean.gi_id = giIds[it] }
                    iuNames.indices
                            .filter { i -> iuNames[i] == AtGongyingshang.text.toString() }
                            .forEach { bean.iu_id = iuIds[it] }
                    mc2Names.indices
                            .filter { i -> mc2Names[i] == AtLeibie.text.toString() }
                            .forEach { bean.mc_2_id = mc2Ids[it] }
                    qiNames.indices
                            .filter { i -> qiNames[i] == AtWenTi.text.toString() }
                            .forEach { bean.qi_id = qiIds[it] }
                    if (bean.gi_id == "") {
                        Myutil.MyTost("货品编码必须填写")
                        return
                    }
                    if (bean.iu_id == "") {
                        Myutil.MyTost("供应商必须填写")
                        return
                    }
                    if (bean.mc_2_id == "") {
                        Myutil.MyTost("材料类别必须填写")
                        return
                    }
                    if (bean.qi_id == "") {
                        Myutil.MyTost("问题代码必须填写")
                        return
                    }
                    bean.jianyan_time=TvJianyanTimeX.text.toString()
                    if(bean.jianyan_time==""){
                        Myutil.MyTost("时间必须输入")
                        return
                    }
                    bean.cailiao_shuliang=EtCailiao.text.toString()
                    bean.choucha_shuliang=EtChoucha.text.toString()
                    bean.hege_shuliang=EtHege.text.toString()
                    bean.quality_decision=SpPanding.selectedItem.toString()
                    bean.process_mode=SpChuLi.selectedItem.toString()
                    bean.solution=EtCaigouJiejue.text.toString()
                    bean.description=EtZhiliangYuanyou.text.toString()
                    updatedialog = Myutil.showupdatedialog(this@CaiLiaoZhiLiangActivity, "正在上传", false)
                    KP.XingjianXiugaiCailiao(bean,deletephoto)
                }
            }
            TvJianyanTimeX -> Dialogutil.showBottoPopupWindow(TvJianyanTimeX, "选择问题发生时间", TvJianyanTimeX.text.toString(), this@CaiLiaoZhiLiangActivity)
            AtGongyingshang -> AtGongyingshang.showDropDown()
            AtHuoping -> AtHuoping.showDropDown()
            AtLeibie -> AtLeibie.showDropDown()
            AtWenTi -> AtWenTi.showDropDown()
        }
    }

    var giIds: ArrayList<String>  = ArrayList<String>()
    var giNames: ArrayList<String>  = ArrayList<String>()
    //获取货品资料数据成功
    override fun HuopingOk(ids: ArrayList<String>, names: ArrayList<String>) {
        UnCeHandler.buzhou="HuopingOk"
        this.giIds = ids
        this.giNames = names
        val av = ArrayAdapter(this@CaiLiaoZhiLiangActivity, android.R.layout.simple_dropdown_item_1line, giNames)
        AtHuoping.setAdapter(av)
        if (cailiaoIt.gi_id != "") {
            giIds.indices
                    .filter { giIds[it] == cailiaoIt.gi_id }
                    .forEach {
                        AtHuoping.setText(giNames[it])
                        Myutil.settv(giNames[it],TvHuoping)
                    }
        }
    }

    //获取货品资料数据失败
    override fun HuopingNo() {
        Myutil.MyTost("获取货品编码列表失败")
    }
    var iuIds: ArrayList<String>  = ArrayList<String>()
    var iuNames: ArrayList<String>  = ArrayList<String>()
    //获取供应商数据成功
    override fun GongyingshangOk(ids: ArrayList<String>, names: ArrayList<String>) {
        UnCeHandler.buzhou="GongyingshangOk"
        this.iuIds = ids
        this.iuNames = names
        val av = ArrayAdapter(this@CaiLiaoZhiLiangActivity, android.R.layout.simple_dropdown_item_1line, iuNames)
        AtGongyingshang.setAdapter(av)
    }
    //获取供应商数据失败
    override fun GongyingshangNo() {
        Myutil.MyTost("获取供应商列表失败")
    }
    var mc2Ids: ArrayList<String>  = ArrayList<String>()
    var mc2Names: ArrayList<String>  = ArrayList<String>()
    //获取材料类别数据成功
    override fun CailiaoLeibieOk(ids: ArrayList<String>, names: ArrayList<String>) {
        UnCeHandler.buzhou="CailiaoLeibieOk"
        this.mc2Ids = ids
        this.mc2Names = names
        val av = ArrayAdapter(this@CaiLiaoZhiLiangActivity, android.R.layout.simple_dropdown_item_1line, mc2Names)
        AtLeibie.setAdapter(av)
    }
    //获取材料类别数据失败
    override fun CailiaoLeibieNo() {
        Myutil.MyTost("获取材料列表列表失败")
    }
    var qiIds: ArrayList<String>  = ArrayList<String>()
    var qiNames: ArrayList<String>  = ArrayList<String>()
    //获取问题代码数据成功
    override fun WentiDaimaOk(ids: ArrayList<String>, names: ArrayList<String>) {
        UnCeHandler.buzhou="WentiDaimaOk"
        this.qiIds = ids
        this.qiNames = names
        val av = ArrayAdapter(this@CaiLiaoZhiLiangActivity, android.R.layout.simple_dropdown_item_1line, qiNames)
        AtWenTi.setAdapter(av)
        if (cailiaoIt.qi_id != "") {
            qiIds.indices
                    .filter { qiIds[it] == cailiaoIt.qi_id }
                    .forEach {
                        AtWenTi.setText(qiNames[it])
                    }
        }
    }
    //获取问题代码数据失败
    override fun WentiDaimaNo() {
        Myutil.MyTost("获取问题代码列表失败")
    }
    //新建材料质量问题成功
    override fun XingjianCailiaoOk() {
        UnCeHandler.buzhou="XingjianCailiaoOk"
        updatedialog.dismiss()
        val i = Intent()
        setResult(Activity.RESULT_OK, i)
        finish()
    }
    //新建材料质量问题失败
    override fun XingjianCailiaoNo() {
        updatedialog.dismiss()
    }
    //修改材料质量问题成功
    override fun XiugaiCailiaoOk() {
        UnCeHandler.buzhou="XiugaiCailiaoOk"
        updatedialog.dismiss()
        val i = Intent()
        setResult(Activity.RESULT_OK, i)
        finish()
    }
    //修改材料质量问题失败
    override fun XiugaiCailiaoNo() {
        updatedialog.dismiss()
    }
    //长按删除照片
    override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
        UnCeHandler.buzhou="onItemLongClick"
        if(code==2) {
            val dialog = AlertDialog.Builder(this@CaiLiaoZhiLiangActivity)
            dialog.setTitle("提示")
            dialog.setMessage("确定要删除这个照片")
            dialog.setPositiveButton("确定") { dialog, which ->
                deletephoto.add(cailiaoIt.listphoto[position])
                cailiaoIt.listphoto.remove(cailiaoIt.listphoto[position])
                photoAdapter.notifyDataSetChanged()
            }
            dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
            dialog.show()
        }
        return true
    }
    //点击查看照片以及添加照片
    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        UnCeHandler.buzhou="onItemClick"
        if (position == cailiaoIt.listphoto.size) {
            Dialogutil.photodialog(this@CaiLiaoZhiLiangActivity, null)
        } else if(position<cailiaoIt.listphoto.size) {
            val intent = Intent(this@CaiLiaoZhiLiangActivity, DanjianivActivity::class.java)
            intent.putExtra("url", cailiaoIt.listphoto[position].uri)
            startActivity(intent)
        }
    }

    //在修改时返回询问是否放弃修改
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        UnCeHandler.buzhou="onKeyDown"
        if (keyCode == 4) {
            if (code == 2) {
                val dialog = AlertDialog.Builder(this@CaiLiaoZhiLiangActivity)
                dialog.setTitle("提示")
                dialog.setMessage("确定要取消上传")
                dialog.setPositiveButton("确定") { dialog, which -> finish() }
                dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                dialog.show()
            }
        }
        return super.onKeyDown(keyCode, event)
    }
    //拍照返回
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        UnCeHandler.buzhou="onActivityResult"
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                99 -> {
                    val selectedImage = data.data
                    if(selectedImage != null){
                        val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                        val c = contentResolver.query(selectedImage, filePathColumns, null, null, null)
                        c!!.moveToFirst()
                        val columnIndex = c.getColumnIndex(filePathColumns[0])
                        val imagePath = c.getString(columnIndex)
                        addphoto(imagePath)
                    }

                }
                100 -> {
                    val name = data.getStringExtra("dir")
                    addphoto(name)
                }
            }
        }
    }

    private fun addphoto(name: String) {
        UnCeHandler.buzhou="addphoto"
        val photo = CaiLiaoZhiLiangBean.photo()
        photo.uri = name
        cailiaoIt.listphoto.add(photo)
        photoAdapter.notifyDataSetChanged()
    }
}
